import 'dart:convert';

import 'package:flutter_component_tool/flutter_components_tools.dart';
import 'package:flutter_multi_env/multi_env.dart';
import 'package:flutter_native_plugins/flutter_native_plugins.dart';

/// 创建单例
/* static HttpsUtils? _instance;
  HttpsUtils._internal() {
    /// 初始化某些需要初始化的东西
  }
  // factory HttpsUtils() => _instance ??= HttpsUtils._internal();
  HttpsUtils get shared => _instance ??= HttpsUtils._internal(); */

String? userToken;

/// Mark ----- 封装基础网络请求工具类
enum MethodType {
  get,
  post,
}

class HttpsUtils {
  /// 服务器域名
  static String serverBaseUrl = '';

  /// Post 请求
  static Future<BaseResponseModel?> post(
    String url, {
    Map<String, dynamic>? parameters,
  }) {
    return BaseRequestExtension._commonRequest(url, type: MethodType.post, parameters: parameters);
  }

  /// Get 请求
  static Future<BaseResponseModel?> get(
    String url, {
    Map<String, dynamic>? parameters,
  }) {
    return BaseRequestExtension._commonRequest(url, type: MethodType.get, parameters: parameters);
  }
}

extension BaseRequestExtension on HttpsUtils {
  static Future<BaseResponseModel?> _commonRequest(
    String url, {
    required MethodType type,
    Map<String, dynamic>? parameters,
  }) async {
    Map<String, String> headers = {};
    Map? result;
    Map? data;

    /// 头部配置
    if (userToken != null) {
      headers["token-app"] = userToken ?? '';
    }

    /// 配置域名
    String rsUrl;
    if (HttpsUtils.serverBaseUrl.isNotEmpty) {
      rsUrl = HttpsUtils.serverBaseUrl + url;
    } else {
      rsUrl = CNMEvn.evnConfig.appDomain + url;
    }

    if (type == MethodType.post) {
      try {
        result = await CNMHttpsPlugins().cnmPost(
          rsUrl,
          parameters: parameters,
          headers: headers,
        );
      } catch (error) {
        throw StateError("抛异常：$error");
      }
    } else if (type == MethodType.get) {
      try {
        result = await CNMHttpsPlugins().cnmGet(
          rsUrl,
          parameters: parameters,
          headers: headers,
        );
      } catch (error) {
        throw StateError("抛异常：$error");
      }
    }

    /// 外层原生模型
    BaseRequestNativeModel nativeModel = BaseRequestNativeModel.fromMap(result);

    if (nativeModel.errorCode != 0) {
      /// toast 提示
      print('错误返回：${nativeModel.errorMessge}');
      return null;
    }

    /// 响应数据模型
    if (!CNMUtils.isBlank(nativeModel.data)) {
      data = jsonDecode(nativeModel.data!); // 解析数据源
    }
    BaseResponseModel responseModel = BaseResponseModel.fromJson(data);

    return responseModel;
  }
}

/// 请求最外层原生包裹模型
class BaseRequestNativeModel {
  /// 请求响应 code（成功返回0）
  final int? errorCode;

  /// 请求响应失败文本
  final String? errorMessge;

  /// 请求响应 data
  final String? data;

  BaseRequestNativeModel({
    this.errorCode,
    this.errorMessge,
    this.data,
  });

  factory BaseRequestNativeModel.fromMap(Map? json) => BaseRequestNativeModel(
        errorCode: json?["error_code"],
        errorMessge: json?["error_message"],
        data: json?["success_data"],
      );
}

/// 请求响应数据模型
class BaseResponseModel {
  /// 响应返回 code
  final int? code;

  /// 响应返回时长
  final String? executeTime;

  /// 响应返回数据正确/失败文本
  final String? msg;

  /// 响应返回数据是否成功
  final bool? succ;

  /// 响应返回数据
  final dynamic data;

  BaseResponseModel({
    this.code,
    this.executeTime,
    this.msg,
    this.succ,
    this.data,
  });

  factory BaseResponseModel.fromJson(Map? json) => BaseResponseModel(
        code: json?["code"],
        executeTime: json?["executeTime"],
        msg: json?["msg"],
        succ: json?["succ"],
        data: json?["data"],
      );
}

/// 元祖类型
class TupleType<E0, E1> {
  final E0? element0;
  final E1? element1;

  TupleType(
    this.element0,
    this.element1,
  );
}
